<template>
  <view class="page-view">
    <view class="header-wrap">
      <view class="header-top">
        <view class="header-left">
          <text class="eqp-name">{{ equipInfo.equType | showEqpType(psEquTypeList) }}</text>
          <view class="online-status">
            <text v-if="equipInfo.onlintStatus === 1" class="un-active">未激活</text>
            <text v-if="equipInfo.onlintStatus === 2" class="online">在线</text>
            <text v-if="equipInfo.onlintStatus === 3" class="outline">离线</text>
          </view>
        </view>
        <view class="header-right" v-if="pipEquipTotal > 1" @click="viewPipInfo">
          <text class="label-text">其它设备</text>
          <u-icon name="arrow-right" color="#E2E2E2" size="18"></u-icon>
        </view>
      </view>
      <view class="info-item">
        <view class="info-label"> 设备名称 </view>
        <view class="info-val">
          {{ equipInfo.equName || '--' }}
        </view>
      </view>
      <view class="info-item">
        <view class="info-label"> 设备编号 </view>
        <view class="info-val">
          {{ equipInfo.equNo || '--' }}
        </view>
      </view>
      <view class="info-item">
        <view class="info-label"> 所属区域 </view>
        <view class="info-val">
          {{ pipPoint.areaName || '--' }}
        </view>
      </view>
      <view class="info-item">
        <view class="info-label"> 所属道路 </view>
        <view class="info-val">
          {{ pipPoint.street || '--' }}
        </view>
      </view>
      <view class="info-item">
        <view class="info-label"> 补偿值 </view>
        <view class="info-val color-blue" @click="handleShowSetCompensate">
          {{ equipInfo.compensate || '--' }}
        </view>
      </view>
      <view class="info-item">
        <view class="info-label"> 井深 </view>
        <view class="info-val" v-if="pipPoint.measureDepth"> {{ pipPoint.measureDepth }} cm </view>
        <view class="info-val" v-else>--</view>
      </view>
      <view class="info-item">
        <view class="info-label"> 经纬度 </view>
        <view class="info-val"> {{ pipPoint.longitude || '' }} ， {{ pipPoint.latitude || '' }} </view>
      </view>
      <view class="info-item">
        <view class="info-label"> 设备经纬度 </view>
        <view class="info-val equip-geo-show">
          <u-icon name="map-fill" size="60rpx" color="#3576F2" @click="handleGeo2address"></u-icon>
          <text v-if="equipInfo.installLongitude">
            {{ equipInfo.installLongitude || '' }} ， {{ equipInfo.installLatitude || '' }}
          </text>
        </view>
      </view>
      <view v-if="showGeo2address" class="info-item">
        <view class="info-label"> </view>
        <view class="info-val equip-geo-show">{{ geo2address }}</view>
      </view>
      <view class="info-item">
        <view class="info-label"> 归属状态 </view>
        <view class="info-val">
          {{ equipInfo.equBelong || '--' }}
        </view>
      </view>			
			<view class="info-item">
			  <view class="info-label"> 管点编号 </view>
			  <view class="info-val">
			    {{ equipInfo.pipPointNo || '--' }}
			  </view>
			</view>
    </view>
    <view class="check-action-wrap">
      <view class="wrap-title"> 在线检测 </view>
      <view class="form-wrap">
        <u--form :model="checkParam" labelPosition="left" :labelWidth="130">
          <u-form-item label="修改采集频率" prop="userInfo.name" borderBottom customStyle="height:80rpx;">
            <u--input
              v-model="checkParam.gatherRate"
              border="none"
              disabled
              disabledColor="#fff"
              fontSize="16"
              color="#000000e6"
            ></u--input>
            <u-icon slot="right" name="arrow-right" color="#E2E2E2" size="18"></u-icon>
          </u-form-item>
          <u-form-item label="修改发送频率" prop="userInfo.name" borderBottom customStyle="height:80rpx;">
            <u--input
              v-model="checkParam.sendRate"
              border="none"
              disabled
              disabledColor="#fff"
              fontSize="16"
              color="#000000e6"
            ></u--input>
            <u-icon slot="right" name="arrow-right" color="#E2E2E2" size="18"></u-icon>
          </u-form-item>
        </u--form>
      </view>
      <view class="action-btn-wrap">
        <view class="check-btn" @click="equipCheck(1)"> 检测 </view>
        <view class="reset-btn" @click="equipCheck(2)"> 还原 </view>
      </view>
    </view>
    <view class="checked-records-wrap">
      <view class="record-title"> 检测记录 </view>
      <view class="record-item" v-for="item in recordList" :key="item.id">
        <view class="record-time">{{ item.reportTime | formatDate }}</view>
        <view class="record-info"> 补偿值：{{ equipInfo.compensate || '--' }}，检测数据：{{ item.deviceData }}，</view>
        <view v-if="equipInfo.compensate >= item.deviceData" class="record-status">状态在线，设备正常。</view>
        <view v-else class="record-status color-red">状态在线，设备异常。</view>
      </view>
    </view>
    <u-modal
      :show="showCompensateDailog"
      title="修改补偿值"
      showCancelButton
      @cancel="showCompensateDailog = false"
      @confirm="handleConfirmCompensate"
    >
      <view class="slot-content">
        <u--input
          v-model="setEquip.compensate"
          type="number"
          placeholder="请输入补偿值"
          border="surround"
          maxlength="6"
          focus
          customStyle="border: 1rpx solid #ededed;width: 480rpx;height: 80rpx;background: #F3F3F3;border-radius: 8rpx;"
        ></u--input>
      </view>
    </u-modal>
    <u-overlay :show="showCheckWaiting">
      <view v-if="dailogType === 1" class="warp wrapone"> 检测中… </view>
      <view v-if="dailogType >= 2" class="warp">
        <view class="check-tip-text" v-if="dailogType > 2"> 检测完成 </view>
        <view class="check-tip-text" :class="{ 'color-blue': dailogType === 3, 'color-red': dailogType === 4 }">
          {{ dailogTip }}
        </view>
        <view class="check-dailog-btns">
          <view class="dailog-btn check-again" @click="handleGetEquipCheckRecords(true)"> 再次检测 </view>
          <view
            class="dailog-btn check-back"
            @click="
              equipCheck(2);
              showCheckWaiting = false;
            "
          >
            完成
          </view>
        </view>
      </view>
    </u-overlay>
  </view>
</template>
<script>
import {
  addEquipOperateLog,
  getEquipInfo,
  equipOnlineCheck,
  getEquipCheckRecords,
  equipPartInfoEdit,
} from '@/api/equip.js';
import { getEqpList } from '@/api/equipmentInstallation.js';
import { getDictItemInfo } from '@/api/system.js';
export default {
  filters: {
    showEqpType(type, psEquTypeList) {
      if (psEquTypeList.length) {
        const showItem = psEquTypeList.find((item) => +item.itemValue === type);
        return showItem?.itemText || '';
      } else {
        return '';
      }
    },
    formatDate(timeString) {
      if (timeString) {
        return timeString.substr(0, 16);
      } else {
        return '--';
      }
    },
  },
  data() {
    return {
      equipId: '',
      equipInfo: {},
      pipPoint: {},
      psEquTypeList: [], // 设备类型字典列表
      recordList: [],
      oldRecord: null,
      checkParam: {
        gatherRate: '1min',
        sendRate: '2min',
      },
      checkType: 2,
      pipEquipTotal: 1,
      eventChannel: null,
      showCompensateDailog: false,
      setEquip: {
        id: '',
        compensate: '',
      },
      showCheckWaiting: false,
      dailogType: 1,
      dailogTip: '未接收到数据',
      timer: null,
      showGeo2address: false,
      geo2address: '',
    };
  },
  onLoad(option) {
    const eventChannel = this.getOpenerEventChannel();
    this.eventChannel = eventChannel;
    eventChannel.on('equipId', (data) => {
      this.equipId = data;
      console.log('equipId', data);
      this.handleGetEquipInfo();
      this.handleGetEquipCheckRecords();
    });

    // this.equipId = "1651582059681951745";
    // this.handleGetEquipInfo();
    // this.handleGetEquipCheckRecords();
  },
  onUnload() {
    this.eventChannel.off('sendEquipInfo');
  },
  created() {
    this.handleGetDictItemInfo('ps_equ_type');
  },
  methods: {
    async handleGetEquipInfo() {
      try {
        const res = await getEquipInfo({
          id: this.equipId || '',
        });
        console.log('equipInfo', res);
        this.equipInfo = res.data.result || {};
        this.pipPoint = res.data.result?.pipPoint || {};
        this.handleGetEquList();
      } catch (e) {
        //TODO handle the exception
      }
    },
    async handleGetEquList() {
      try {
        const { data } = await getEqpList({
          pipPointNo: this.pipPoint.pipNo,
          pageNo: 1,
          pageSize: 20,
        });
        this.pipEquipTotal = data?.result?.total || 1;
      } catch (e) {
        //TODO handle the exception
      }
    },
    async handleGetEquipCheckRecords(flag) {
      try {
        const res = await getEquipCheckRecords({
          id: this.equipId || '',
        });
        // console.log('records', res.data.result);
        const recordList = res.data.result || [];
        if (flag) {
          const deviceData = recordList[0].deviceData;
          if (recordList[0].id === this.oldRecord.id) {
            this.dailogType = 2;
            this.dailogTip = '未接收到数据';
          } else if (this.equipInfo.compensate >= deviceData) {
            this.dailogType = 3;
            this.dailogTip = `检测数据：${deviceData}，数据正常`;
          } else if (this.equipInfo.compensate < deviceData) {
            this.dailogType = 4;
            this.dailogTip = `检测数据：${deviceData}，数据异常`;
          }
        }
        // 只显示一条数据
        this.oldRecord = recordList[0];
        this.recordList = recordList.filter((item, i) => i === 0);
      } catch (e) {
        //TODO handle the exception
      }
    },
    async handleGetDictItemInfo(dictCode) {
      try {
        const { data } = await getDictItemInfo({
          dictCode,
        });
        this.psEquTypeList = data?.result || [];
      } catch (e) {
        //TODO handle the exception
      }
    },
    handleShowSetCompensate(equip) {
      this.setEquip.id = this.equipId;
      this.setEquip.compensate = this.equipInfo.compensate || '';
      this.showCompensateDailog = true;
    },
    async handleConfirmCompensate(val) {
      try {
        const setEquipId = this.equipId;
        const newCompensate = this.setEquip.compensate;
        const param = {
          id: setEquipId,
          compensate: newCompensate,
        };
        await equipPartInfoEdit(param);
        this.handleGetEquipInfo();
        this.showCompensateDailog = false;
      } catch (e) {
        //TODO handle the exception
      }
    },
    viewPipInfo() {
      uni.navigateTo({
        url: '/pages/equipmentInstallation/equipmentInstallation',
        success: (res) => {
          res.eventChannel.emit('routeShowWellInfo', this.pipPoint);
        },
      });
    },
    async equipCheck(type) {
      try {
        const { pipPointNo, equNo, equType, onlintStatus } = this.equipInfo;
        const operationParams = {
          pointNo: pipPointNo,
          equNo,
          equType,
          status: onlintStatus,
          operateType: 6,
          operateSource: 2,
          operateTime: new Date().format('yyyy-MM-dd hh:mm:ss'),
        };
        await addEquipOperateLog(operationParams);
        this.dailogType = 1;
        await equipOnlineCheck({
          id: this.equipId,
          type,
        });
        if (type === 1) {
          let sendRate = this.checkParam.sendRate;
          sendRate = +sendRate.substring(0, sendRate.length - 3);
          console.log(sendRate * 1000);
          // const timeDuration = sendRate*1000; // 测试
          const timeDuration = sendRate * 60 * 1000 + 5000;
          this.showCheckWaiting = true;
          this.timer = setTimeout(() => {
            this.handleGetEquipCheckRecords(true);
            this.dailogType = 2;
          }, timeDuration);
        }
      } catch (e) {
        //TODO handle the exception
      }
    },
    handleGeo2address() {
      this.showGeo2address = !this.showGeo2address;
      if (!this.showGeo2address) {
        return;
      }
      uni.getLocation({
        type: 'wgs84',
        altitude: true,
        isHighAccuracy: true,
        geocode: true,
        success: (res) => {
          const geoStr = res.longitude + ',' + res.latitude;
          this.queryAddress(geoStr);
        },
      });
    },
    async queryAddress(geoStr) {
      try {
        const res = await uni.request({
          url: 'https://restapi.amap.com/v3/geocode/regeo', //仅为示例，并非真实接口地址。
          data: {
            key: 'd65ffff104bc21f79b3eb5d9e1d1840a',
            location: geoStr,
          },
        });
        const addressComponent = res[1].data.regeocode.addressComponent;
        const { city, district, township, streetNumber } = addressComponent;
        this.geo2address = city + district + township + streetNumber.street + streetNumber.number;
        uni.showToast({
          title: '已获取当前坐标地址',
        });
        this.showGeo2address = true;
      } catch (e) {
        //TODO handle the exception
      }
    },
    hideKeyboard() {
      uni.hideKeyboard();
    },
  },
};
</script>
<style lang="scss" scoped>
.equip-detail-page {
  min-height: 100vh;
  background-color: #fff;
}

.page-view {
  min-height: 100vh;
}

.header-wrap {
  background-color: #fff;
  padding: 24rpx 48rpx;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 33rpx;
}

.header-left {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.eqp-name {
  height: 50rpx;
  margin-right: 14rpx;
  line-height: 50rpx;
  font-weight: 500;
  font-size: 36rpx;
  color: #000000e6;
}

.online,
.un-active {
  padding: 2rpx 8rpx;
  background: #dae7ff;
  border-radius: 4rpx;
  font-size: 24rpx;
  color: #3576f2;
}

.outline {
  padding: 2rpx 6rpx;
  background: #ffdada;
  border-radius: 4rpx;
  font-size: 24rpx;
  color: #f23535;
}

.header-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.label-text {
  font-weight: 400;
  font-size: 30rpx;
  color: #000000e6;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;

  & + & {
    margin-top: 8rpx;
  }
}

.info-label {
  height: 40rpx;
  line-height: 40rpx;
  font-size: 30rpx;
  color: #00000099;
}

.equip-geo-show {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.check-action-wrap {
  margin: 24rpx;
  padding: 24rpx;
  background-color: #fff;
  border-radius: 16px;
}

.wrap-title {
  margin-bottom: 16rpx;
  font-size: 36rpx;
  color: #000000e6;
}

.action-btn-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 48rpx 0;
}

.checked-records-wrap {
  margin: 0 24rpx 56rpx;
  padding: 24rpx;
  background-color: #fff;
  border-radius: 16px;
  font-size: 28rpx;
  color: #00000099;
}

.check-btn {
  box-sizing: border-box;
  width: 315rpx;
  height: 96rpx;
  line-height: 96rpx;
  text-align: center;
  background: #3576f2;
  border-radius: 8px;
  font-size: 36rpx;
  color: #ffffff;
}

.reset-btn {
  box-sizing: border-box;
  width: 315rpx;
  height: 96rpx;
  line-height: 96rpx;
  text-align: center;
  font-size: 36rpx;
  color: #3576f2;
  border: 2px solid #3576f2;
  border-radius: 8px;
}

.record-title {
  padding-bottom: 16rpx;
  margin-bottom: 16rpx;
  font-size: 36rpx;
  color: #363a44;
  border-bottom: 1rpx solid #e7e7e7;
}

.record-item {
  margin-bottom: 24rpx;
}

.warp {
  width: 560rpx;
  min-height: 221rpx;
  border-radius: 16rpx;
  background-color: #fff;
  display: position;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

.wrapone {
  text-align: center;
  line-height: 221rpx;
}

.check-tip-text {
  margin: 32rpx 0;
  text-align: center;
  font-size: 32rpx;
  color: #000000e6;
}

.check-dailog-btns {
  display: flex;
  justify-content: stretch;
  align-items: center;
  height: 99rpx;
  border-top: 1rpx solid #e5e5e5;
}

.dailog-btn {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36rpx;
  color: #000000e6;
}

.check-back {
  color: #3576f2;
}

.color-blue {
  color: #3576f2;
}

.color-red {
  color: #f23535;
}
</style>
